package handler

import (
	"context"
	"gozero-microservices/gateway-api/define"
	"gozero-microservices/gateway-api/internal/logic"
	"gozero-microservices/gateway-api/internal/types"
	"net/http"

	"github.com/zeromicro/go-zero/rest/httpx"
)

/*
 +----------------------------------------------------------------------
 + Title        : OrderHandler
 + Author       : huwl
 + Version      : 1.0.0
 + Initial-Time : 2025-10-26
 + Last-time    : 这个文件最后修改的时间 + 修改人的名称
 + Desc         : 订单处理器
 +----------------------------------------------------------------------
*/

type OrderHandler struct {
	BaseHandler
}

/**
 * 下单
 *
 * @param uint64 GoodsSkuId -------------------必传,商品规格选项
 * @param uint8 Num ---------------------------必传,商品数量
 * @param uint8 Platform ----------------------必传,商城平台
 * @param string Username ---------------------必传,用户名
 * @param uint64 AddressId --------------------必传,收货地址ID
 * @return json
 * @author huwl
 * @date 2025/10/20 18:51:38
 */
func (control *OrderHandler) GenerateOrder(w http.ResponseWriter, r *http.Request) {
	var req types.OrderCreateRequest
	if err := httpx.Parse(r, &req); err != nil {
		control.BaseError(r, w, control.WithMessage(err.Error()))
		return
	}

	// 调用逻辑层
	orderLogic := logic.NewOrderLogicInstance(context.Background(), control.SvcCtx)
	oid, err := orderLogic.GenerateOrder(req)
	if err != nil {
		control.BaseError(r, w, control.WithGrpcError(err))
		return
	}

	control.BaseSuccess(r, w, control.WithMessage("下单成功"), control.WithData(map[string]interface{}{
		"oid": oid,
	}))
}

/**
 * 下单
 *
 * @param uint64 GoodsSkuId -------------------必传,商品规格选项
 * @param uint8 Num ---------------------------必传,商品数量
 * @param uint8 Platform ----------------------必传,商城平台
 * @param string Username ---------------------必传,用户名
 * @param uint64 AddressId --------------------必传,收货地址ID
 * @return json
 * @author huwl
 * @date 2025/10/20 18:51:38
 */
func (control *OrderHandler) List(w http.ResponseWriter, r *http.Request) {
	var req types.QueryOrderRequest
	if err := httpx.Parse(r, &req); err != nil {
		control.BaseError(r, w, control.WithMessage(err.Error()))
		return
	}

	// 调用逻辑层
	orderLogic := logic.NewOrderLogicInstance(context.Background(), control.SvcCtx)
	result, err := orderLogic.OrderList(req)
	if err != nil {
		control.BaseError(r, w, control.WithGrpcError(err))
		return
	}

	control.BaseSuccess(r, w, control.WithData(map[string]interface{}{
		"page":         result.Page,
		"page_size":    result.PageSize,
		"total":        result.Total,
		"page_total":   result.PageTotal,
		"orders":       result.Orders,
		"order_status": define.GetAllOrderStatus(),
	}))
}
